﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gfw.Repositories.Account;
using Gfw.Repositories.Views;
using Gfw.Repository;

namespace Gfw.Infrastructure.Facilities
{
    /// <summary>
    /// 对碰奖，应该在系统空闲时间调用
    /// 对碰奖260*10%，（左右区各加入1单方可对碰、每层的对碰封顶为180对，日封顶3000元）
    /// </summary>
    public class PairAward : IFacility
    {
        private const decimal BaseAward = 260;
        private const decimal Ratio = 0.1M;
        private const int MaxPair = 220;
        private const decimal MaxAward = 3000;

        private DateTime _end;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="end">结算截至时间</param>
        public PairAward(DateTime end)
        {
            _end = end;
        }

        public void Execute(Repository.UnitOfWork unitOfWork = null)
        {
            UnitOfWork work = unitOfWork ?? new UnitOfWork();
            ActSystemRepository systemRep = new ActSystemRepository();
            var actSystem = systemRep.Unique(work);

            UserCountRepository countRep = new UserCountRepository();
            var list = countRep.Query(actSystem.PairDate.Value, _end);

            //已经获得了所有用户的统计数字，现在可以开始计算对碰奖励
            foreach (var l in list)
            {
                try
                {
                    var oldPair = Math.Min(l.OldLeftChildren, l.OldRightChildren);
                    var newPair = Math.Min(l.OldLeftChildren + l.NewLeftChildren,
                                           l.OldRightChildren + l.NewRightChildren);
                    //如果没有配对，则跳出循环
                    if (newPair - oldPair == 0)
                        continue;
                    //计算对碰奖的奖金
                    decimal award = (newPair - oldPair) * BaseAward * Ratio;
                    //核查奖金的最大数
                    //if (award > MaxAward) award = MaxAward;

                    CompanyDynamicAward cda = new CompanyDynamicAward(l.Id, award, Account.UserTradeTypeEnum.Pair,
                                                                      Account.CompanyTradeTypeEnum.Pair);
                    cda.Execute();
                }
                catch (Exception exp)
                {
                    //这里应该记录系统日志，以备查阅

                }

            }

            //更新系统信息表
            actSystem.PairDate = _end;
            systemRep.Update(actSystem);
            if (unitOfWork == null)
                work.Commit();

        }
    }
}
